'use strict';

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('LifeCycle');

var status = {
	not_init: 'not_init',
	init_ing: 'init_ing',
	init_done: 'init_done',
	start_ing: 'start_ing',
	ready: 'ready',
	pause: 'pause',
	stop_ing: 'stop_ing',
	stop: 'stop'
};


function LifeCycle() {
	this.status = status.not_init;
}

util.inherits(LifeCycle, EventEmitter);
module.exports = LifeCycle;

/**
 * init LifeCycle, after init, a
 * event 'init_done' is emit
 */
LifeCycle.prototype.__init = function() {
	console.log('__init');
	var self = this;
	self.status = status.init_ing;
	self.init(function() {
		self.status = 'init_done';
		self.emit('init_done');
	});
};

LifeCycle.prototype.init = function(cb) {}

/**
 * start LifeCycle, after done, a
 * event 'start_done' is emit
 */
LifeCycle.prototype.__start = function() {
	console.log('__start');
	var self = this;
	self.status = status.start_ing;
	self.start(function() {
		self.status = status.ready;
		self.emit('ready');
	});
};
LifeCycle.prototype.start = function(cb) {};

/**
 * start LifeCycle, after done, a
 * event 'start_done' is emit
 */
LifeCycle.prototype.__stop = function() {
	console.log('__stop');
	var self = this;
	this.status = status.stop_ing;
	self.stop(function() {
		self.status = status.stop;
		self.emit('stop');
	});

};
LifeCycle.prototype.stop = function(cb) {};

LifeCycle.prototype.getStatus = function() {
	return this.getStatus;
};

LifeCycle.prototype.__errorHandler = function(err) {
	console.log('__errorHandler');
	if (this.errorHandler && typeof(this.errorHandler) === 'function') {
		this.errorHandler(err);
	} else {
		console.log('should have a errorHandler');
		throw error;
	}
};


/**
 * general LifeCycle flow
 */
LifeCycle.prototype.go = function() {
	console.log('go');
	if (this.status === status.ready) {
		console.log('server in ready status');
		return;
	}
	this.__init();
	this.on('init_done', this.__start);
	this.on('error', this.__errorHandler);
};